package com.ieslab.powergrid.demosvr.service;

import com.ieslab.powergrid.demosvr.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class TestAsyncService {
    @Autowired
    private JedisPool jedisPool;

    @Async
    public Result getRedis433(String key){
        System.out.println(key+":启动getRedis433");
        getRedis41(key);
        System.out.println(key+":完成getRedis433");
        return null;
    }

    @RequestMapping("getRedis41")
    public Result getRedis41(String key){
        long startTime = System.currentTimeMillis();
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //使用管道方式，性能比单次获取性能高
            Pipeline pipeline = jedis.pipelined();
            Map<String, Response<String>> map = new HashMap<>();
            Response<Set<String>> keys = pipeline.keys(key);
            pipeline.sync();
            Set<String> sets = keys.get();
            // System.out.println(System.currentTimeMillis() - startTime);
            // System.out.println("-----sets:" + sets.size());
            for(String ketTmp :sets){
                try {
                    Response<String> sResponse= pipeline.get(ketTmp);
                    map.put(ketTmp,sResponse);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            pipeline.sync();
            int i = sets.size()-10;
            for (Map.Entry<String, Response<String>> entry : map.entrySet()) {
                Response<String> sResponse=(Response<String>)entry.getValue();
                if(i<sets.size()){
                    // if(sResponse.get() == null){
                    // System.out.println(entry.getKey()+"-----" + sResponse.get());
                    // }
                }
                ++i;
            }
            long haoshi = System.currentTimeMillis() - startTime;
            System.out.println("个数：" + map.size() + "；耗时:" + haoshi+ "；大小:" +  map.toString().getBytes().length/1024);


        } finally {
            //返还到连接池
            jedis.close();
        }
        return Result.ok(System.currentTimeMillis() - startTime);
    }
}
